﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.ApplicationBlocks.Data;
using System.Data;
using System.Data.SqlClient;
using Newtonsoft.Json;

namespace MyTemplate
{
    public class ArticleManager
    {


        public SqlDataReader getArticles(string filterText)
        {
            string query = "Select ID,Title,Link from tbArticles ";

            if (filterText.Equals(""))
            {
                query += ";";
            }
            else
            {
                query += " where Title like '%'+@filterText+'%' ;";
            }

            return SqlHelper.ExecuteReader(SqlHelper.DbConnectionString, CommandType.Text, query, new SqlParameter[] { new SqlParameter("@filterText", filterText) });
        }

        public string getArticlesJSON(string filterText)
        {
            SqlDataReader reader = getArticles(filterText);

            var r = Serialize(reader);
            string json = JsonConvert.SerializeObject(r, Formatting.Indented);
            //Console.WriteLine(json);

            //{ totalpages = 20, page = 1, totalrecords = 100, json = [
            //"total":10, "page":10, "records":10, "rows": [

            return "{\"total\":10, \"page\":10, \"records\":10, \"rows\":"+json+" }";
        }
        public IEnumerable<Dictionary<string, object>> Serialize(SqlDataReader reader)
        {
            var results = new List<Dictionary<string, object>>();
            var cols = new List<string>();
            for (var i = 0; i < reader.FieldCount; i++)
                cols.Add(reader.GetName(i));

            while (reader.Read())
                results.Add(SerializeRow(cols, reader));

            return results;
        }
        private Dictionary<string, object> SerializeRow(IEnumerable<string> cols,
                                                        SqlDataReader reader)
        {
            var result = new Dictionary<string, object>();
            foreach (var col in cols)
                result.Add(col, reader[col]);
            return result;
        }
    }
}